<?php
/**
 * File containing the BRail_Netbios_Recognition class.
 * @package BRail_Netbios
 * @deprecated deprecated since version 1.3.0
 */

/**
 * @package BRail_Netbios
 * @deprecated deprecated since version 1.3.0
 */
class BRail_Netbios_Recognition
{
    /**
     * Command used under MS Windows to display ip adresses assigned to network interfaces
     */
    const WIN_GETIP_COMMAND = 'ipconfig';

    /**
     * Command used under MS Windows to lookup an ip address via Netbios
     */
    const WIN_LOOKUP_COMMAND = 'nbtstat -a';

    /**
     * Command used under SUNOS for same purpose
     */
    const SUN_LOOKUP_COMMAND = '/usr/local/samba/bin/nmblookup -A';

    /**
     * Command used under Linux for same purpose
     */
    const LIN_LOOKUP_COMMAND = 'nmblookup -A';

    /**
     * Try to get the login via netbios
     * @return string|false either a login or error
     */
    public static function getLogin()
    {
        // First, we need to define the LAN IP address of the caller
        $ipAddress = $_SERVER['REMOTE_ADDR']; // Default case

        // We handle the special case where the client connects from the same host as the server
        // (While developing under windows)
        if ($ipAddress === '127.0.0.1') {
            $matches = array();
            preg_match(
                '/IP Address[. ]+: ([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})/',
                shell_exec(self::WIN_GETIP_COMMAND),
                $matches
            );
            $ipAddress = $matches[1];
        }

        // Secondly, we choose the lookup command depending on the server host OS
        switch (strtolower(PHP_OS)) {
            case 'winnt':
                $cmd = self::WIN_LOOKUP_COMMAND;
                break;
            case 'sunos':
                $cmd = self::SUN_LOOKUP_COMMAND;
                break;
            case 'linux':
                $cmd = self::LIN_LOOKUP_COMMAND;
                break;
            default:
                // Cannot happen
        }
        $cmd .= ' ' . $ipAddress;

        // Finally, we lookup for the login
        $matches = array();
        preg_match(
            '/([A-Z]{3}[0-9]{3,4})/',
            shell_exec($cmd),
            $matches
        );

        // If the result looks like a login, we return it else we return false
        $matchLength = strlen($matches[0]);
        if (isset($matches[0]) && ($matchLength === 6 || $matchLength === 7)) {
            return $matches[0];
        }
        return false;
    }
}
